#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>

#define		IS_NUM(car)		(car >= 60 && car <= 71)

#define		BKS		'\n'
#define		TAB		'\t'
#define		SPC		' '
#define		COM		'/'
#define		NUL		'\0'
#define		INC		'%'
#define		STR		'"'


int main (void){

	acf_load ("aures.acf");
	return 0;
}

int acf_error (const char *format, ...)
/*
	
*/
{
 va_list ap;
 char buffer[512];
 int gard;

 	va_start (ap, format);
	vsnprintf (buffer, sizeof (buffer), format, ap);
	va_end (ap);

	printf ("%s", buffer);

 return 0;
}

char* strip_blanks (char* buf){
	char* ptr = buf;
	char* revptr = buf + strlen(buf) - 1;


	while ((*ptr == SPC)||(*ptr == TAB)){
		ptr++;
	}

	while ((*revptr == SPC)||(*revptr == TAB)){
		*ptr = NUL;
		ptr --;
	}

	return ptr;

}

int acf_load (const char* fname){
	char buffer[512];
	char *ptr = NULL;
	int line = 0;

	FILE* fp = fopen (fname, "r");
		if (fp == NULL){
			acf_error ("%s: no such file or directory\n", fname);
			return -1;
		}

	while (!feof(fp)){

		fgets (buffer, sizeof(buffer)-1, fp);
		line++;

		/*strip prefixed and postfixed blanks*/
		ptr = strip_blanks (buffer);

		/*check for comment*/
		if (ptr[0] == COM){
			if (ptr[1] != COM){
				acf_error ("%s:%d: Invalid token '/'\n", fname, line);
				return -1;
			}
		}
		else /* check for an include */
		if (ptr[0] == INC){
			ptr++;
			if (strncmp (ptr, "include", 7) == 0){
				ptr = ptr + 7;
				ptr = strip_blanks (ptr);
				if (ptr[0] == STR){
					char* file = strtok(ptr, "\"");
					acf_load (file);
					ptr = ptr + strlen(file) + 2;
					if (ptr[0] != BKS && ptr[0] != COM){
						acf_error ("%s:%d: Invalid token '%s'\n", fname, line, ptr);
					}
					else
					if (ptr[0] == COM && ptr[1] != COM){
						acf_error ("%s:%d: Invalid token '%s'\n", fname, line, ptr);
					}
				}
				else
				{
					ptr[strlen(ptr) - 1] = NUL;
					acf_error ("%s:%d: Invalid token '%s'\n", fname, line, ptr);
				}
			}
			else
			{
				ptr[strlen(ptr) - 1] = NUL;
				acf_error ("%s:%d: Invalid token '%s'\n", fname, line, ptr);
			}

		}

	}

	fclose (fp);
	fp = NULL;

 return 0;
}
